import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import type { AsyncThunk, ActionReducerMapBuilder, PayloadAction, Slice } from '@reduxjs/toolkit'
import { getNotice, type GetNoticeParams } from './noticeAPI'
import { DataType } from "@/pages/Notice/Table";

interface InitialState {
  params: GetNoticeParams,
  table: {
    status: 'init' | 'loading' | 'success' | 'error',
    data: Res | undefined,
    params?: GetNoticeParams
  },
  modal: {
    type: 'create' | 'update'
    open: boolean,
    record?: DataType
  }
}

const initialState:InitialState = {
  params: {
    announce_type: '',
    page: 1,
    page_size: 10,
  },
  table: {
    status: "init",
    data: undefined,
  },
  modal: {
    type: 'create',
    open: false,
  }
};

type Res = {
  data: {
    count:number,
    page: number,
    data: DataType[]
  }
}
type AsyncRes = {
  data: Res,
  params: GetNoticeParams
}
export const getNoticeAsync:AsyncThunk<AsyncRes, GetNoticeParams, {}> = createAsyncThunk<AsyncRes, GetNoticeParams, {}>(
  "notice/getNoticeAsync",
  async (params) => {
    const res:Res = await getNotice(params);
    return {
      data: res,
      params
    };
  }
);
const tableStatus:(builder:ActionReducerMapBuilder<InitialState>)=>void = (builder:ActionReducerMapBuilder<InitialState>):void => {
  builder
    .addCase(getNoticeAsync.pending, (state:InitialState):void => {
      state.table.status = "loading";
    })
    .addCase(getNoticeAsync.fulfilled, (state:InitialState, action:PayloadAction<AsyncRes>):void => {
      state.table.status = "success";
      state.table.data = action.payload.data;
      state.table.params = action.payload.params
    })
    .addCase(getNoticeAsync.rejected, (state:InitialState):void => {
      state.table.status = "error";
    });
};

type Reducers = {
  changeParams:(state:InitialState, action:PayloadAction<Partial<GetNoticeParams>>)=>void,
  changeModal: (state:InitialState, action:PayloadAction<Partial<InitialState['modal']>>) => void
}
type Selectors = {}
const noticeSlice:Slice<InitialState,Reducers,'notice','notice',Selectors> = createSlice<InitialState, Reducers, 'notice', Selectors, 'notice'>({
  name: "notice",
  initialState,
  reducers: {
    changeParams(state:InitialState, action:PayloadAction<Partial<GetNoticeParams>>):void {
      state.params = {
        ...state.params,
        ...action.payload,
      };
    },
    changeModal(state, action){
      state.modal = {
        ...state.modal,
        ...action.payload
      }
    }
  },
  extraReducers(builder:ActionReducerMapBuilder<InitialState>):void {
    tableStatus(builder);
  },
});

export const { changeParams, changeModal }:typeof noticeSlice.actions = noticeSlice.actions;

export default noticeSlice.reducer;
